<?php
namespace Mapi\Controller;
use Think\Controller;

class IndexController extends Controller
{

	private $_a = '';
	private $_m = '';

	public function _initialize()
	{
		//测试代码 上线去掉
		if(empty($_POST))
		{
			 $_POST = $_GET;
		}
		else
		{
			$_POST=array_merge($_POST,$_GET);
		}
		//数据加密校验 @TODO
		$v = $_GET['v'];
		$v = $v ? $v : '1.0';
		$method = $_GET['method'];
		if(!preg_match('/^[A-Za-z0-9]+\.[A-Za-z0-9]+$/i', $method))
		{
			$this->apiReturn(1,'unvalid method');
		}
		$tmp = explode('.', $method);
		$aname = '\Mapi\Controller\V'.str_replace('.', '_', $v).'\\'.ucfirst($tmp[0]).'Controller';

		// $a = '\Admin\Controller\IndexController';
		if(!class_exists($aname))
		{
			$this->apiReturn(1, 'unvalid method1');
		}
		$a = new $aname();
		$this->_a = $a;
		$m = $tmp[1];
		// var_dump($a,$m);

		if(!method_exists($a, $m))
		{
			$this->apiReturn(1, 'unvalid method2');
		}
		$this->_m = $m;
	}

	//mapi 入口
	public function index()
	{
		if (version_compare(phpversion(), '7.0') < 0)
		{
			call_user_method($this->_m, $this->_a);
		}
		else
		{
			call_user_func(array( $this->_a, $this->_m)); 	
		}
		
	}

	/**
	 * 校验数据加密 完整性
	 */

	/**
	 * 格式化mapi的返回格式
	 */
	protected function apiReturn($code = 0, $msg = '', $data = '')
	{
		$json = array(
			'code' => $code,
			'data' => $data,
			'message' => $msg,
			);
		array_walk_recursive($json, 'stripNull');
		$this->ajaxReturn($json, 'json');
	}
}